package com.bdy.lm.isu.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bdy.lm.common.model.Driver;
import com.bdy.lm.common.model.ISUMesaage;
import com.bdy.lm.common.model.MsgID;
import com.bdy.lm.common.utils.JsonUtil;
import com.bdy.lm.isu.service.ISUService;
import com.google.gson.Gson;

@Controller
public class ISUController {

	@Autowired
	private ISUService isuService;
	private Logger logger = Logger.getLogger(ISUController.class);
	
	@RequestMapping(value = "/isu", method = RequestMethod.POST)//
	public void processISURequest(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("application/Json;charset=utf-8");
			ServletInputStream sis = request.getInputStream();
			DataInputStream dataInStream = new DataInputStream(sis);
			byte[] buf = new byte[1024];
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			int n = dataInStream.read(buf);
			while (n != -1) {
				os.write(buf, 0, n);
				n = dataInStream.read(buf);
			}
			byte[] res = os.toByteArray();
			System.out.println("result:" + new String(res));
			JsonUtil.writerJsonToResponse(getResult(new String(res)), response);
		} catch (Exception e) {
			logger.error("ISUController 异常：" + e);
		}
	}
	
	private String getResult(String request) {
		ISUMesaage msg = new Gson().fromJson(request, ISUMesaage.class);
		String result = "";
		switch (msg.getMsgId()) {
			case MsgID.LOGIN:
				result = isuService.login(msg);
				break;
			case MsgID.LOGOUT:
				break;
			default:
				break;
		}
		return result;
	}
}
